$(document).ready(function() {
        // 评论审核页面JS逻辑
        $(function() {
            // 全局变量
            let currentPage = 1;
            const pageSize = 10;
            const auditStatusMap = {
                '1': '待审核',
                '2': '审核通过',
                '3': '审核拒绝',
                '4': '再次审核'
            };

            // 初始化页面
            init();

            /**
             * 初始化函数
             */
            function init() {
                loadCommentStats();
                initTableData();
                initCheckboxEvents();
                initActionEvents();
                initBatchOperations();
                initFilterEvents();
                initModalEvents();
            }

            /**
             * 加载评论列表
             */
            function initTableData() {
                // 显示加载中状态
                $('#commentTableBody').html('<tr><td colspan="9" class="text-center py-4">加载中...</td></tr>');
                
                // 获取筛选参数
                const params = getFilterParams();
                
                // 调用后端接口获取数据
                fetchCommentList(params)
                    .then(result => {
                        renderTable(result.data.list);
                        renderPagination(result.data.total, currentPage, pageSize);
                        updateBatchButtons();
                    })
                    .catch(error => {
                        $('#commentTableBody').html('<tr><td colspan="9" class="text-center py-4 text-danger">加载数据失败，请重试</td></tr>');
                    });
            }

            /**
             * 获取筛选参数
             */
            function getFilterParams() {
                return {
                    currentPage,
                    pageSize,
                    claimStatus: $('#claimStatusFilter').val(),
                    relatedType: $('#relatedTypeFilter').val(),
                    auditStatus: $('#statusFilter').val(),
                    sortType: $('#sortFilter').val(),
                    keyword: $('#keywordSearch').val().trim(),
                    userId: $('#userIdSearch').val().trim(),
                    startDate: $('#startDate').val(),
                    endDate: $('#endDate').val(),
                    contentType: $('#contentTypeFilter').val(), // 新增内容类型筛选
                    relatedId: $('#relatedIdSearch').val().trim()
                };
            }

            /**
             * 渲染表格数据（优化后）
             */
            function renderTable(data) {
                const tableBody = $('#commentTableBody');
                tableBody.empty();
                
                if (data.length === 0) {
                    tableBody.append(`
                        <tr>
                            <td colspan="10" class="px-5 py-10 text-center text-neutral-500">
                                <i class="fa fa-comment-o text-3xl mb-2"></i>
                                <p>没有找到匹配的言论数据</p>
                            </td>
                        </tr>
                    `);
                    return;
                }
                
                // 构建评论父子关系映射
                const commentMap = {};
                const rootComments = [];
                data.forEach(item => {
                    commentMap[item.comment_id] = item;
                    item.children = [];
                    if (!item.parent_id) {
                        rootComments.push(item);
                    } else {
                        // 找到父评论并添加到子列表
                        if (commentMap[item.parent_id]) {
                            commentMap[item.parent_id].children.push(item);
                        } else {
                            // 父评论不在当前页时也作为根评论显示
                            rootComments.push(item);
                        }
                    }
                });
                
                // 递归渲染评论（支持层级）
                function renderComment(comment, level = 0) {
                    const isReply = level > 0;
                    const isClaimed = comment.claimed_status === "2";
                    const hasSensitive = comment.has_sensitive === "1";
                    const isAnonymous = comment.is_anonymous === "1";
                    
                    // 内容类型图标
                    const contentIcons = {
                        "1": '<i class="fa fa-file-text-o text-neutral-400 mr-1"></i>',
                        "2": '<i class="fa fa-picture-o text-neutral-400 mr-1"></i>',
                        "3": '<i class="fa fa-link text-neutral-400 mr-1"></i>'
                    };
                    const contentIcon = contentIcons[comment.content_type] || '';
                    
                    // 处理敏感词高亮
                    let contentHtml = comment.content;
                    if (hasSensitive && comment.sensitive_words) {
                        const sensitiveWords = comment.sensitive_words.split(',');
                        sensitiveWords.forEach(word => {
                            contentHtml = contentHtml.replace(
                                new RegExp(word, 'g'), 
                                `<span class="bg-yellow-100 text-danger font-medium">${word}</span>`
                            );
                        });
                    }
                    
                    // 审核状态标签样式
                    const statusStyles = {
                        "1": '<span class="px-2 py-1 text-xs rounded-full bg-blue-100 text-blue-600"><i class="fa fa-clock-o mr-1"></i>待审核</span>',
                        "2": '<span class="px-2 py-1 text-xs rounded-full bg-green-100 text-green-600"><i class="fa fa-check mr-1"></i>通过</span>',
                        "3": '<span class="px-2 py-1 text-xs rounded-full bg-red-100 text-red-600"><i class="fa fa-times mr-1"></i>拒绝</span>',
                        "4": '<span class="px-2 py-1 text-xs rounded-full bg-orange-100 text-orange-600"><i class="fa fa-refresh mr-1"></i>再次审核</span>'
                    };
                    
                    // 认领状态
                    const claimStatus = isClaimed 
                        ? `<span class="px-2 py-1 text-xs rounded-full bg-success/10 text-success">已认领</span>`
                        : `<span class="px-2 py-1 text-xs rounded-full bg-neutral-100 text-neutral-500">未认领</span>`;
                    
                    // 认领信息
                    const claimInfo = isClaimed 
                        ? `审核员: ${comment.claimed_by_name || comment.claimed_by}<br>${formatDateTime(comment.claimed_time)}`
                        : '未认领';
                    
                    // 操作按钮
                    let operateButtons = '';
                    if ([1, 4].includes(Number(comment.audit_status))) {
                        operateButtons = `
                            <div class="flex space-x-1">
                                <button class="text-primary hover:text-primary/80 text-sm view-detail" data-id="${comment.comment_id}" title="查看详情">
                                    <i class="fa fa-eye"></i>
                                </button>
                                ${!isClaimed ? `<button class="text-primary hover:text-primary/80 text-sm claim-comment" data-id="${comment.comment_id}" title="认领">
                                    <i class="fa fa-hand-paper-o"></i>
                                </button>` : ''}
                                <button class="text-success hover:text-success/80 text-sm approve-comment" data-id="${comment.comment_id}" ${!isClaimed ? 'disabled title="请先认领"' : 'title="通过"'}>
                                    <i class="fa fa-check"></i>
                                </button>
                                <button class="text-danger hover:text-danger/80 text-sm reject-comment" data-id="${comment.comment_id}" ${!isClaimed ? 'disabled title="请先认领"' : 'title="拒绝"'}>
                                    <i class="fa fa-times"></i>
                                </button>
                                <button class="text-warning hover:text-warning/80 text-sm review-comment" data-id="${comment.comment_id}" ${!isClaimed ? 'disabled title="请先认领"' : 'title="标记复查"'}>
                                    <i class="fa fa-flag"></i>
                                </button>
                            </div>
                        `;
                    } else {
                        operateButtons = `
                            <div class="flex space-x-1">
                                <button class="text-primary hover:text-primary/80 text-sm view-detail" data-id="${comment.comment_id}" title="查看详情">
                                    <i class="fa fa-eye"></i>
                                </button>
                                <button class="text-neutral-400 text-sm" disabled title="已处理">
                                    <i class="fa fa-check"></i>
                                </button>
                                <button class="text-neutral-400 text-sm" disabled title="已处理">
                                    <i class="fa fa-times"></i>
                                </button>
                            </div>
                        `;
                    }
                    
                    // 行样式（交替色+层级缩进）
                    const rowClass = level % 2 === 0 ? 'bg-white' : 'bg-neutral-50';
                    const indentStyle = isReply ? `padding-left: ${level * 20 + 5}px;` : '';
                    
                    tableBody.append(`
                        <tr class="${rowClass} hover:bg-neutral-50/50 transition-colors">
                            <td class="px-5 py-4">
                                <input type="checkbox" class="collection-item-checkbox rounded border-neutral-300 text-primary focus:ring-primary" data-id="${comment.comment_id}">
                            </td>
                            <td class="px-5 py-4 text-sm font-medium">${comment.comment_id}</td>
                            <td class="px-5 py-4 max-w-xs" style="${indentStyle}">
                                ${isReply ? `<div class="inline-block w-4 h-4 -mt-1 mr-1 text-neutral-300">↳</div>` : ''}
                                <div class="font-medium">${contentIcon}${contentHtml}</div>
                                ${hasSensitive ? `<div class="text-xs text-danger mt-1"><i class="fa fa-exclamation-triangle mr-1"></i>含敏感词</div>` : ''}
                            </td>
                            <td class="px-5 py-4 text-sm">
                                <div>${comment.related_type === 'none' ? '无' : 
                                    comment.related_type === 'collection' ? '合集' : 
                                    comment.related_type === 'media' ? '媒体' : comment.related_type}</div>
                                <div class="text-neutral-500 text-xs">ID: ${comment.related_id || '-'}</div>
                            </td>
                            <td class="px-5 py-4 text-sm">
                                <div>
                                    ${comment.user_nickname} 
                                    ${isAnonymous ? '<i class="fa fa-user-secret text-neutral-400 ml-1" title="匿名"></i>' : ''}
                                </div>
                                <div class="text-neutral-500 text-xs">ID: ${comment.submit_user_id}</div>
                            </td>
                            <td class="px-5 py-4 text-sm text-neutral-600">${formatDateTime(comment.submit_time)}</td>
                            <td class="px-5 py-4">
                                <div>${claimStatus}</div>
                                <div class="text-neutral-500 text-xs mt-1">${claimInfo}</div>
                            </td>
                            <td class="px-5 py-4">${statusStyles[comment.audit_status] || '-'}</td>
                            <td class="px-5 py-4 text-sm">${comment.chk_num || 0}</td>
                            <td class="px-5 py-4">${operateButtons}</td>
                        </tr>
                    `);
                    
                    // 递归渲染子评论
                    if (comment.children && comment.children.length > 0) {
                        comment.children.forEach(child => renderComment(child, level + 1));
                    }
                }
                
                // 渲染所有根评论
                rootComments.forEach(comment => renderComment(comment));
            }

            /**
             * 渲染分页控件
             */
            function renderPagination(total, currentPage, pageSize) {
                const totalPages = Math.ceil(total / pageSize);
                const paginationContainer = $('#commentPagination').empty();
                
                // 上一页按钮
                const prevDisabled = currentPage === 1 ? 'disabled' : '';
                paginationContainer.append(`
                    <button class="w-8 h-8 flex items-center justify-center rounded border border-neutral-200 text-neutral-400 hover:border-primary hover:text-primary disabled:opacity-50 pagination-btn" 
                            data-page="${currentPage - 1}" ${prevDisabled}>
                        <i class="fa fa-angle-left"></i>
                    </button>
                `);
                
                // 页码按钮（最多显示5个页码）
                let startPage = Math.max(1, currentPage - 2);
                let endPage = Math.min(totalPages, startPage + 4);
                
                if (endPage - startPage < 4 && totalPages > 5) {
                    startPage = Math.max(1, endPage - 4);
                }
                
                for (let i = startPage; i <= endPage; i++) {
                    const isActive = i === currentPage ? 'border-primary bg-primary text-white' : 'border-neutral-200 text-neutral-700 hover:border-primary hover:text-primary';
                    paginationContainer.append(`
                        <button class="w-8 h-8 flex items-center justify-center rounded ${isActive} pagination-btn" data-page="${i}">
                            ${i}
                        </button>
                    `);
                }
                
                // 下一页按钮
                const nextDisabled = currentPage === totalPages ? 'disabled' : '';
                paginationContainer.append(`
                    <button class="w-8 h-8 flex items-center justify-center rounded border border-neutral-200 text-neutral-400 hover:border-primary hover:text-primary disabled:opacity-50 pagination-btn" 
                            data-page="${currentPage + 1}" ${nextDisabled}>
                        <i class="fa fa-angle-right"></i>
                    </button>
                `);
                
                // 更新分页信息
                const start = total > 0 ? (currentPage - 1) * pageSize + 1 : 0;
                const end = Math.min(currentPage * pageSize, total);
                $('.pagenation').text(`显示 ${start} 至 ${end} 条，共 ${total} 条`);
            }

            /**
             * 初始化复选框事件
             */
            function initCheckboxEvents() {
                // 全选/取消全选
                $('#selectAll').change(function() {
                    const isChecked = $(this).is(':checked');
                    $('.collection-item-checkbox').prop('checked', isChecked);
                    updateBatchButtons();
                });
                
                // 单个复选框事件
                $(document).on('change', '.collection-item-checkbox', function() {
                    const allChecked = $('.collection-item-checkbox:checked').length === $('.collection-item-checkbox').length;
                    $('#selectAll').prop('checked', allChecked);
                    updateBatchButtons();
                });
            }

            /**
             * 更新批量操作按钮状态
             */
            function updateBatchButtons() {
                const checkedCount = $('.collection-item-checkbox:checked').length;
                $('#selectedCount').text(`已选择 ${checkedCount} 项`);
                
                const hasChecked = checkedCount > 0;
                $('#batchClaimBtn').prop('disabled', !hasChecked);
                $('#batchApproveBtn').prop('disabled', !hasChecked);
                $('#batchRejectBtn').prop('disabled', !hasChecked);
                $('#batchReviewBtn').prop('disabled', !hasChecked);
            }

            /**
             * 初始化筛选事件
             */
            function initFilterEvents() {
                // 筛选按钮
                $('#filterBtn').click(function() {
                    currentPage = 1; // 重置为第一页
                    initTableData();
                });
                
                // 重置按钮
                $('#resetBtn').click(function() {
                    $('#claimStatusFilter').val('0');
                    $('#relatedTypeFilter').val('');
                    $('#statusFilter').val('');
                    $('#sortFilter').val('0');
                    $('#keywordSearch').val('');
                    $('#userIdSearch').val('');
                    $('#startDate').val('');
                    $('#endDate').val('');
                    $('#relatedIdSearch').val('');
                    
                    currentPage = 1;
                    initTableData();
                });
            }

            /**
             * 初始化操作按钮事件
             */
            function initActionEvents() {
                // 查看详情
                $(document).on('click', '.view-detail', function() {
                    const commentId = $(this).data('id');
                    showCommentDetail(commentId);
                });

                // 分页按钮点击事件
                $(document).on('click', '.pagination-btn', function() {
                    const page = parseInt($(this).data('page'));
                    if (!isNaN(page) && page !== currentPage) {
                        currentPage = page;
                        initTableData();
                    }
                });
                
                // 认领评论
                $(document).on('click', '.claim-comment', function() {
                    const commentId = $(this).data('id');
                    showClaimModal(commentId);
                });
                
                // 审核通过
                $(document).on('click', '.approve-comment', function() {
                    const commentId = $(this).data('id');
                    batchOperate([commentId], 'approve')
                        .then(() => {
                            initTableData();
                            showToast('审核通过成功', 'success');
                        })
                        .catch(() => {
                            showToast('审核通过失败，请重试', 'error');
                        });
                });
                
                // 审核拒绝
                $(document).on('click', '.reject-comment', function() {
                    const commentId = $(this).data('id');
                    showRejectModal([commentId]);
                });
                
                // 标记复查
                $(document).on('click', '.review-comment', function() {
                    const commentId = $(this).data('id');
                    showReviewModal([commentId]);
                });
            }

            /**
             * 初始化批量操作事件
             */
            function initBatchOperations() {
                // 批量认领
                $('#batchClaimBtn').click(function() {
                    const checkedItems = $('.collection-item-checkbox:checked');
                    const ids = Array.from(checkedItems).map(item => $(item).data('id'));
                    
                    if (ids.length === 0) {
                        showToast('请选择要认领的记录', 'warning');
                        return;
                    }
                    
                    batchOperate(ids, 'claim')
                        .then(() => {
                            initTableData();
                            showToast('批量认领成功', 'success');
                        })
                        .catch(() => {
                            showToast('批量认领失败，请重试', 'error');
                        });
                });
                
                // 批量通过
                $('#batchApproveBtn').click(function() {
                    const checkedItems = $('.collection-item-checkbox:checked');
                    const ids = Array.from(checkedItems).map(item => $(item).data('id'));
                    
                    if (ids.length === 0) {
                        showToast('请选择要通过的记录', 'warning');
                        return;
                    }
                    
                    batchOperate(ids, 'approve')
                        .then(() => {
                            initTableData();
                            showToast('批量通过成功', 'success');
                        })
                        .catch(() => {
                            showToast('批量通过失败，请重试', 'error');
                        });
                });
                
                // 批量拒绝
                $('#batchRejectBtn').click(function() {
                    const checkedItems = $('.collection-item-checkbox:checked');
                    const ids = Array.from(checkedItems).map(item => $(item).data('id'));
                    
                    if (ids.length === 0) {
                        showToast('请选择要拒绝的记录', 'warning');
                        return;
                    }
                    
                    showRejectModal(ids);
                });
                
                // 批量标记复查
                $('#batchReviewBtn').click(function() {
                    const checkedItems = $('.collection-item-checkbox:checked');
                    const ids = Array.from(checkedItems).map(item => $(item).data('id'));
                    
                    if (ids.length === 0) {
                        showToast('请选择要标记复查的记录', 'warning');
                        return;
                    }
                    
                    showReviewModal(ids);
                });
            }

            /**
             * 初始化模态框事件
             */
            function initModalEvents() {
                // 关闭认领模态框
                $('#cancelClaimBtn').click(function() {
                    $('#claimModal').removeClass('flex').addClass('hidden');
                });
                
                // 确认认领
                $('#confirmClaimBtn').click(function() {
                    const commentId = $(this).data('id');
                    $('#claimModal').removeClass('flex').addClass('hidden');
                    
                    batchOperate([commentId], 'claim')
                        .then(() => {
                            initTableData();
                            showToast('认领成功', 'success');
                        })
                        .catch(() => {
                            showToast('认领失败，请重试', 'error');
                        });
                });
                
                // 关闭确认模态框
                $('#cancelBtn').click(function() {
                    $('#confirmModal').removeClass('flex').addClass('hidden');
                });

                // 关闭评论详情模态框
                $('#closeCommentDetailModal, #closeCommentDetailBtn').on('click', function() {
                    $('#commentDetailModal').addClass('hidden').removeClass('flex');
                });
                
                // 确认操作（通用）
                $('#confirmBtn').click(function() {
                    const commentId = $(this).data('id');
                    const action = $(this).data('action');
                    $('#confirmModal').removeClass('flex').addClass('hidden');
                    
                    batchOperate([commentId], action)
                        .then(() => {
                            initTableData();
                            showToast(`${action === 'approve' ? '通过' : '操作'}成功`, 'success');
                        })
                        .catch(() => {
                            showToast(`${action === 'approve' ? '通过' : '操作'}失败，请重试`, 'error');
                        });
                });
                
                // 关闭拒绝模态框
                $('#closeRejectModal, #cancelReject').click(function() {
                    $('#rejectModal').removeClass('flex').addClass('hidden');
                });
                
                // 确认拒绝
                $('#confirmReject').click(function() {
                    const ids = $(this).data('ids');
                    const rejectType = $('#rejectTypeSelect').val();
                    const remark = $('#rejectRemark').val().trim();
                    
                    if (!rejectType) {
                        showToast('请选择拒绝类型', 'warning');
                        return;
                    }
                    
                    $('#rejectModal').removeClass('flex').addClass('hidden');
                    
                    batchOperate(ids, 'reject', { rejectType, remark })
                        .then(() => {
                            initTableData();
                            showToast('拒绝操作成功', 'success');
                        })
                        .catch(() => {
                            showToast('拒绝操作失败，请重试', 'error');
                        });
                });
                
                // 关闭复查模态框
                $('#closeReviewModal, #cancelReview').click(function() {
                    $('#reviewModal').removeClass('flex').addClass('hidden');
                });
                
                // 确认标记复查
                $('#confirmReview').click(function() {
                    const ids = $(this).data('ids');
                    const remark = $('#reviewRemark').val().trim();
                    
                    $('#reviewModal').removeClass('flex').addClass('hidden');
                    
                    batchOperate(ids, 'review', { remark })
                        .then(() => {
                            initTableData();
                            showToast('标记复查成功', 'success');
                        })
                        .catch(() => {
                            showToast('标记复查失败，请重试', 'error');
                        });
                });
                
                // 关闭详情模态框
                $('#closeDetailModal').click(function() {
                    $('#collectionDetailModal').removeClass('flex').addClass('hidden');
                });
            }

            /**
             * 显示认领模态框
             */
            function showClaimModal(commentId) {
                $('#claimMessage').text(`您确定要认领言论 [${commentId}] 吗？认领后其他审核员将无法操作。`);
                $('#claimModal').removeClass('hidden').addClass('flex');
                $('#confirmClaimBtn').data('id', commentId);
            }

            /**
             * 显示通过模态框
             */
            function showApproveModal(commentId) {
                $('#modalTitle').text('审核通过确认');
                $('#modalMessage').text(`您确定要通过言论 [${commentId}] 的审核吗？`);
                $('#confirmModal').removeClass('hidden').addClass('flex');
                $('#confirmBtn').data('id', commentId).data('action', 'approve');
            }

            /**
             * 显示拒绝模态框
             */
            function showRejectModal(ids) {
                // batchOperate(ids, 'reject')
                $('#rejectTypeSelect').val('');
                $('#rejectRemark').val('');
                $('#rejectModal').removeClass('hidden').addClass('flex');
                $('#confirmReject').data('ids', ids);
            }

            /**
             * 显示复查模态框
             */
            function showReviewModal(ids) {
                $('#reviewRemark').val('');
                $('#reviewModal').removeClass('hidden').addClass('flex');
                $('#confirmReview').data('ids', ids);
            }

            /**
             * 显示评论详情
             */
            function showCommentDetail(commentId) {
                // 显示加载状态
                $('#commentDetailContent').html(`
                    <div class="flex justify-center items-center py-10">
                        <div class="animate-spin rounded-full h-8 w-8 border-t-2 border-b-2 border-primary"></div>
                        <span class="ml-2 text-neutral-600">加载中...</span>
                    </div>
                `);
                // 修正：使用评论详情模态框ID
                $('#commentDetailModal').removeClass('hidden').addClass('flex');

                // 调用接口获取详情
                fetch(`/system/getCommentDetail?commentId=${encodeURIComponent(commentId)}`, {
                    method: 'GET',
                    headers: {
                        'Authorization': `Bearer ${localStorage.getItem('token')}`
                    }
                })
                .then(response => {
                    if (!response.ok) throw new Error('获取详情失败');
                    return response.json();
                })
                .then(result => {
                    if (result.status/1 !== 0 || !result.data) {
                        throw new Error(result.message || '获取详情数据失败');
                    }
                    renderCommentDetail(result.data);
                })
                .catch(error => {
                    $('#commentDetailContent').html(`
                        <div class="py-10 text-center">
                            <i class="fa fa-exclamation-circle text-danger text-xl mb-2"></i>
                            <p class="text-neutral-600">${error.message || '获取详情失败，请重试'}</p>
                            <button onclick="showCommentDetail(${commentId})" class="mt-3 px-4 py-1 bg-primary text-white rounded hover:bg-primary/90">
                                重新加载
                            </button>
                        </div>
                    `);
                });
            }

            /**
             * 渲染评论详情
             */
            function renderCommentDetail(data) {

                const detailHtml = `
                    <div class="grid grid-cols-1 md:grid-cols-3 gap-6">
                        <div class="md:col-span-2">
                            <div class="mb-6">
                                <h4 class="text-sm text-neutral-500 mb-1">言论ID</h4>
                                <p class="font-medium">${data.comment_id || '-'}</p>
                            </div>
                            
                            <div class="mb-6">
                                <h4 class="text-sm text-neutral-500 mb-1">言论内容</h4>
                                <div class="bg-neutral-50 p-3 rounded-lg text-neutral-700">${data.content || '无内容'}</div>
                            </div>
                            
                            <div class="mb-6">
                                <h4 class="text-sm text-neutral-500 mb-1">关联信息</h4>
                                <div class="bg-neutral-50 p-3 rounded-lg">
                                    <div class="mb-2">类型: ${data.related_type || '-'}</div>
                                    <div>ID: ${data.related_id || '-'}</div>
                                    ${data.related_name ? `<div class="mt-2">名称: ${data.related_name}</div>` : ''}
                                </div>
                            </div>
                        </div>
                        
                        <div>
                            <div class="bg-neutral-50 p-4 rounded-lg mb-6">
                                <h4 class="text-sm font-medium mb-3">审核信息</h4>
                                
                                <div class="mb-3">
                                    <div class="text-xs text-neutral-500">审核状态</div>
                                    <div class="mt-1">${auditStatusMap[data.audit_status] || '未知状态'}</div>
                                </div>
                                
                                <div class="mb-3">
                                    <div class="text-xs text-neutral-500">审核次数</div>
                                    <div class="mt-1 text-sm">${data.audit_count || 0} 次</div>
                                </div>
                                
                                <div class="mb-3">
                                    <div class="text-xs text-neutral-500">发表用户</div>
                                    <div class="mt-1 text-sm">${data.user_id || '-'}</div>
                                </div>
                                
                                <div class="mb-3">
                                    <div class="text-xs text-neutral-500">发表时间</div>
                                    <div class="mt-1 text-sm">${data.publish_time ? formatDateTime(data.publish_time) : '-'}</div>
                                </div>
                                
                                <div class="mb-3">
                                    <div class="text-xs text-neutral-500">IP地址</div>
                                    <div class="mt-1 text-sm">${data.ip_address || '-'}</div>
                                </div>
                                
                                <div class="mb-3">
                                    <div class="text-xs text-neutral-500">认领状态</div>
                                    <div class="mt-1">
                                        ${data.claimed_status/1==2 
                                            ? `<span class="px-2 py-1 text-xs rounded-full bg-success/10 text-success">已认领</span>` 
                                            : `<span class="px-2 py-1 text-xs rounded-full bg-neutral-100 text-neutral-500">未认领</span>`
                                        }
                                    </div>
                                </div>
                                
                                ${data.claimed_by ? `
                                <div class="mb-3">
                                    <div class="text-xs text-neutral-500">认领人</div>
                                    <div class="mt-1 text-sm">审核员ID: ${data.claimed_by}</div>
                                </div>
                                
                                <div>
                                    <div class="text-xs text-neutral-500">认领时间</div>
                                    <div class="mt-1 text-sm">${data.claimed_time ? formatDateTime(data.claimed_time) : '-'}</div>
                                </div>
                                ` : ''}
                            </div>
                        </div>
                    </div>
                `;
                
                $('#commentDetailContent').html(detailHtml);
                $('#operateFromDetailBtn').data('id', data.comment_id);
            }

            /**
             * 批量操作API调用
             */
            async function batchOperate(ids, action, extraParams = {}) {
                try {
                    let url = '';
                    let requestData = { ids: ids ,
                    ...extraParams};

                    switch(action) {
                        case 'approve':
                            url = '/system/BatchAuditPassComment';
                            break;
                        case 'reject':
                            url = '/system/BatchAuditRejectComment';
                            // 获取拒绝类型（通过模态框）
                            const rejectType = $('#rejectTypeSelect').val();
                            if (!rejectType) {
                                throw new Error('请选择拒绝类型');
                            }
                            requestData.rejectType = rejectType;
                            requestData.remark = $('#rejectRemark').val().trim() || '';
                            break;
                        case 'review':  // 添加复查操作支持
                            url = '/system/BatchMarkReviewComment';  // 假设的后端API地址
                            requestData.remark = $('#reviewRemark').val() || '';  // 可选备注
                            break;
                        case 'claim':  // 添加认领操作支持
                            url = '/system/BatchClaimComment';  // 假设的后端API地址
                            requestData.remark = $('#claimRemark').val() || '';  // 可选备注
                            break;
                        default:
                            throw new Error('不支持的操作类型');
                    }

                    const response = await fetch(url, {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                            'Authorization': `Bearer ${localStorage.getItem('token')}`
                        },
                        body: JSON.stringify(requestData)
                    });

                    const result = await response.json();
                    
                    if (!response.ok || result.status/1 !== 0) {
                        throw new Error(result.msg || `操作失败: ${response.statusText}`);
                    }
                    
                    return result;
                } catch (error) {
                    throw error; // 抛出错误给调用方处理
                }
            }

            /**
             * 获取评论列表API
             */
            function fetchCommentList(params) {
                return new Promise((resolve, reject) => {
                    $.ajax({
                        url: `/system/GetCommentListForPage`,
                        method: 'GET',
                        data: params,
                        headers: {
                            'Authorization': `Bearer ${localStorage.getItem('token')}`
                        },
                        success: (result) => {
                            if (result.status/1 === 0) {
                                resolve(result);
                            } else {
                                reject(result.message || '获取数据失败');
                            }
                        },
                        error: () => {
                            reject('网络错误，请重试');
                        }
                    });
                });
            }

            
            /**
             * 格式化日期时间
             */
            function formatDateTime(dateString) {
                if (!dateString) return '';
                const date = new Date(dateString);
                return `${date.getFullYear()}-${(date.getMonth()+1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}:${date.getSeconds().toString().padStart(2, '0')}`;
            }
        
            /**
             * 获取统计数据
             */
            async function loadCommentStats() {        
                try {
                    // 发起请求
                    const response = await fetch(`/system/GetCommentStats`, {
                        method: 'GET',
                        headers: {
                            // GET请求无需设置Content-Type（无请求体）
                            'Authorization': `Bearer ${localStorage.getItem('token')}`
                        }
                    });

                    if (!response.ok) { // 更规范的状态判断
                        throw new Error(`请求失败: ${response.statusText}`);
                    }

                    const result = await response.json(); // 仅解析一次响应体
                    const stats = result.data;

                    if (!stats) {
                        throw new Error('统计数据格式异常');
                    }

                    console.log(stats);

                    // 更新待审核言论数据
                    if (stats.pending) {
                        $('#pendingCount').text(stats.pending.total);
                        const pendingTrend = stats.pending.trend;
                        const pendingPercent = stats.pending.percent;
                        const pendingTrendEl = $('#pendingCount').closest('.bg-white').find('.flex.items-center.text-sm span:first-child');
                        pendingTrendEl.html(`
                            <i class="fa fa-arrow-${pendingTrend === 1 ? 'up' : pendingTrend === -1 ? 'down' : 'right'} mr-1"></i> 
                            ${Math.abs(pendingPercent)}%
                        `);
                        pendingTrendEl.removeClass('text-success text-danger').addClass(
                            pendingTrend === 1 ? 'text-danger' : pendingTrend === -1 ? 'text-success' : 'text-neutral-400'
                        );
                    }

                    // 更新今日已审核数据
                    if (stats.audited) {
                        $('#todayApprovedCount').text(stats.audited.total);
                        const auditedTrend = stats.audited.trend;
                        const auditedPercent = stats.audited.percent;
                        const auditedTrendEl = $('#todayApprovedCount').closest('.bg-white').find('.flex.items-center.text-sm span:first-child');
                        auditedTrendEl.html(`
                            <i class="fa fa-arrow-${auditedTrend === 1 ? 'up' : auditedTrend === -1 ? 'down' : 'right'} mr-1"></i> 
                            ${Math.abs(auditedPercent)}%
                        `);
                        auditedTrendEl.removeClass('text-success text-danger').addClass(
                            auditedTrend === 1 ? 'text-success' : auditedTrend === -1 ? 'text-danger' : 'text-neutral-400'
                        );
                    }

                    // 更新已拒绝合集数据
                    if (stats.violation) {
                        $('#violationCount').text(stats.violation.total);
                        const rejectedTrend = stats.violation.trend;
                        const rejectedPercent = stats.violation.percent;
                        const rejectedTrendEl = $('#violationCount').closest('.bg-white').find('.flex.items-center.text-sm span:first-child');
                        rejectedTrendEl.html(`
                            <i class="fa fa-arrow-${rejectedTrend === 1 ? 'up' : rejectedTrend === -1 ? 'down' : 'right'} mr-1"></i> 
                            ${Math.abs(rejectedPercent)}%
                        `);
                        rejectedTrendEl.removeClass('text-success text-danger').addClass(
                            rejectedTrend === 1 ? 'text-danger' : rejectedTrend === -1 ? 'text-success' : 'text-neutral-400'
                        );
                    }

                    // 更新平均审核时长数据
                    if (stats.avgHandleTime) {
                        $('#avgHandleTime').text(`${stats.avgHandleTime.minutes} 分钟`);
                        const timeTrend = stats.avgHandleTime.trend;
                        const timePercent = stats.avgHandleTime.percent;
                        const timeTrendEl = $('#avgHandleTime').closest('.bg-white').find('.flex.items-center.text-sm span:first-child');
                        timeTrendEl.html(`
                            <i class="fa fa-arrow-${timeTrend === 1 ? 'up' : timeTrend === -1 ? 'down' : 'right'} mr-1"></i> 
                            ${Math.abs(timePercent)}%
                        `);
                        timeTrendEl.removeClass('text-success text-danger').addClass(
                            timeTrend === 1 ? 'text-danger' : timeTrend === -1 ? 'text-success' : 'text-neutral-400'
                        );
                    }

                    return result; // 返回解析后的完整结果

                } catch (error) {
                    // 确保showToast已定义，否则替换为console.error
                    if (typeof showToast === 'function') {
                        showToast(error.message || '获取统计数据失败');
                    } else {
                        console.error(error.message || '获取统计数据失败');
                    }
                }
            }
        
        });
    })